/*
 * Copyright (c) 2011-2012 Alexander Dubu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * o  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * o  Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * o  Neither the name Axil nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package axil.framework.localization;

import axil.etc.Identity;
import axil.framework.localization.loader.ResourceFileLoader;
import axil.framework.localization.loader.ResourceLoader;
import axil.framework.localization.xml.ResourceElement;
import axil.framework.localization.xml.ResourceSet;

import java.util.*;


/**
 * A namespace is an object that creates a hierarchy of identities, allowing
 * for logical grouping and separation of assets. All translatable assets are
 * within a specific namespace. All of Axil is within the "axil" root namespace
 * or one of its subsidiary namespaces.
 */
public class Namespace implements Identity {
	private static final int size = Locality.all().size();
	private static final List<ResourceLoader> loaders =
	    new ArrayList<ResourceLoader>();
	static {
		loaders.add(new ResourceFileLoader());
	}

	public static final Namespace
	root = new Namespace(),
	axil = new Namespace(root, "axil");

	private Namespace parent;
	private String ident;
	private boolean[] loaded;
	private HashMap<String,Translation> resources;
	private Map<String,Namespace> children;


	private Namespace() {
		resources = new HashMap<String, Translation>();
		children = new HashMap<String, Namespace>();
	}


	private Namespace(Namespace parent, String ident) {
		this();
		this.parent = parent;
		this.ident = ident;
		this.loaded = new boolean[size];
	}


	/**
	 * Get the unique identity for this object. The string returned is never
	 * empty and contains no punctuation characters beyond a possible '-'. The
	 * value is suitable for use as an identifier.
	 */
	public String identity() {
		return ident;
	}


	/**
	 * Get the parent of this namespace. The namespace returned is only null
	 * for the anonymous root namespace.
	 */
	public Namespace parent() {
		return parent;
	}


	private StringBuilder walk(StringBuilder b, char ch) {
		if (this != root) {
			if (parent != null) {
				parent.walk(b, ch);
			}
			if (b.length() > 0) {
				b.append(ch);
			}
			b.append(ident);
		}
		return b;
	}


	public String path() {
		return this.walk(new StringBuilder(), '/').toString();
	}


	public String dotted() {
		return walk(new StringBuilder(), '.').toString();
	}


	private synchronized void load(Locality locale) {
		HashMap<String,Translation> map = resources;
		ResourceSet res = null;
		Iterator<ResourceLoader> i = loaders.iterator();
		while ((res == null) && i.hasNext()) {
			res = i.next().load(locale, this);
		}
		if (res != null) {
			for (ResourceElement e : res) {
				Translation t = map.get(e.key());
				if (t == null) {
					if (map == resources) {
						map = (HashMap<String,Translation>)resources.clone();
					}
					t = new Translation(e.key());
					map.put(e.key(), t);
				}
				t.apply(locale, e);
			}
		}
		resources = map;
		loaded[locale.index()] = true;
	}


	public Translation translation(String key, Locality locale) {
		if (! loaded[locale.index()]) {
			load(locale);
		}
		Translation t = resources.get(key);
		if (t == null) {
			Locality fallback = locale.fallback();
			if (fallback == null) {
				t = new Translation(key);
			} else {
				t = translation(key, fallback);
			}
		}
		return t;
	}


	public synchronized Namespace ns(String ident) {
		Namespace ns = children.get(ident);
		if (ns == null) {
			ns = new Namespace(this, ident);
			children.put(ident, ns);
		}
		return ns;
	}
}
